import { getUser, setUser,getToken, setToken, removeToken} from '@/utils/auth'
import {login,loginByPhoneCheck,register} from '@/api/login'
import {Message} from 'element-ui'
import Cookies from 'js-cookie'
import router from '@/router'

const user={
  state:{
    user:getUser(),//调用方法获取cookie中的user
    loginToken:getToken()
  },
  mutations:{
    SET_USER:(state,user)=>{
      state.user=user
    },
    set_TOKEN:(state,token)=>{
      state.loginToken=token
    }
  },
  actions:{
    //登陆
    Login({commit},user){
      user.user_name=user.user_name.trim()//去掉空格
      return new Promise((resolve,reject)=>{
        //执行post请求登陆
        login(user.user_name,user.user_password).then(res=>{
          console.log("登陆成功,store储存用户信息",res);
          setToken(res.data.loginToken);//在cookie中设置token
          commit('set_TOKEN',res.data.loginToken);//在store中保存token
          commit('SET_USER',res.data.user);//在store中保存user
          setUser(res.data.user)//在cookie中设置user
          Message.success({message:'登陆成功'})
          resolve()
        }).catch(error=>{
          reject(error)
        })
      })
    },
		
	//手机验证码登陆
	LoginByPhoneCheck({commit},form){
	 form.userPhone=form.userPhone.trim()//去掉空格
	 form.code=form.code.trim()//去掉空格
	  return new Promise((resolve,reject)=>{
		//执行post请求登陆
		console.log("执行到这里")
		loginByPhoneCheck(form.userPhone,form.code).then(res=>{
		  console.log("登陆成功,store储存用户信息",res);
		  setToken(res.data.loginToken);//在cookie中设置token
		  commit('set_TOKEN',res.data.loginToken);//在store中保存token
		  commit('SET_USER',res.data.user);//在store中保存user
		  setUser(res.data.user)//在cookie中设置user
		  Message.success({message:'登陆成功'})
		  resolve()
		}).catch(error=>{	
		  reject(error)
		})
	  })
	},

    //注销
    Logout({commit}){
      return new Promise((resolve,reject) =>{
        commit('set_TOKEN','');//清空store中user和token
        commit('SET_USER','');
        setToken('');//清空cookie中的token和user
        setUser('')
        Message.success({message:'注销成功'})
        resolve()
      }).catch(error=>{
        reject(error)
      })
    },

    //注册
    Register({commit},user){
      user.user_name=user.user_name.trim()//去掉空格
      return new Promise((resolve,reject) =>{
        register(user.user_name,user.user_password,user.user_password2).then(res=>{
          console.log("注册,store储存用户信息",res);
          setToken(res.data.loginToken);//在cookie中设置token
          commit('set_TOKEN',res.data.loginToken);//在store中保存token
          commit('SET_USER',res.data.user);//在store中保存user
          setUser(res.data.user)//在cookie中设置user
          Message.success({message:'注册成功'})
          resolve()
        }).catch(error=>{
          reject(error)
        })
      })
    },

    //更新本地用户信息
    UpdateUser({commit},user){
      console.log("更新用户信息",user);
    	commit('SET_USER',user) //设置用户信息
    	setUser(user)  //设置到cookie中
    }
  }
}

export default user
